﻿// TestSocketPair.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include"../SocktTcp/XTcp.h"
#include"../XThread/XThread.h"
#include<WinSock2.h>
#pragma comment(lib,"ws2_32.lib")



class ReadSocketPair :public XThread
{
public:
	ReadSocketPair() {};
	void SetReadSocket(int sock)
	{
		_readSocket = sock;
	}
	/////线程主函数
	virtual void Main()
	{
		while (!isExit)
		{
			if (_readSocket == 0)
			{
				XSleep(2);
				continue;
			}
			int n = recv(_readSocket, _readBuf, sizeof(_readBuf) - 1, 0);
			if (n > 0)
			{
				std::cout << "recvbuf :" << _readBuf << std::endl;
			}
			XSleep(10);
		}
	}
	int _readSocket = 0;
	char _readBuf[1024] = { 0 };
};


class WriteSocketPair :public XThread
{
public:
	WriteSocketPair() {};
	void SetWriteBuf(char* buf, int len)
	{
		memset(_writeBuf, 0, sizeof(_writeBuf));
		if (len > sizeof(_writeBuf)) len = sizeof(_writeBuf) - 1;
		strncpy_s(_writeBuf, buf, len);
	}
	void SetWriteSocket(int sock)
	{
		_writeSocket = sock;
	}
	/////线程主函数
	virtual void Main()
	{

		while (!isExit)
		{
			if (_writeSocket == 0)
			{
				XSleep(2);
				continue;
			}
			int n = send(_writeSocket, _writeBuf, strlen(_writeBuf), 0);
			XSleep(1000);
		}
	}
	int _writeSocket = 0;
	char _writeBuf[1024] = { 0 };

};

int main()
{
	XTcp tcp[2];
	XTcp::CreatePariSocket(tcp);


	WriteSocketPair writer;
	writer.SetWriteSocket(tcp[0].sock);
	char buf[] = "write send hello world\n";
	writer.SetWriteBuf(buf, sizeof(buf));

	WriteSocketPair writer1;
	writer1.SetWriteSocket(tcp[1].sock);
	char buf1[] = "write12 send hello world\n";
	writer1.SetWriteBuf(buf1, sizeof(buf1));

	ReadSocketPair reader;
	reader.SetReadSocket(tcp[1].sock);


	ReadSocketPair reader1;
	reader1.SetReadSocket(tcp[0].sock);



	writer1.Start();
	reader1.Start();

	writer.Start();
	reader.Start();

	getchar();
}

// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单

// 入门使用技巧: 
//   1. 使用解决方案资源管理器窗口添加/管理文件
//   2. 使用团队资源管理器窗口连接到源代码管理
//   3. 使用输出窗口查看生成输出和其他消息
//   4. 使用错误列表窗口查看错误
//   5. 转到“项目”>“添加新项”以创建新的代码文件，或转到“项目”>“添加现有项”以将现有代码文件添加到项目
//   6. 将来，若要再次打开此项目，请转到“文件”>“打开”>“项目”并选择 .sln 文件
